package nio;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Instruction：基于NIO的文件拷贝
 * Author：@author MaLi
 */
public class FileCopy {
    @Test
    public void fileCopy() {
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        try {
            FileInputStream fileInputStream = new FileInputStream("pom.xml");
            FileChannel inChannel = fileInputStream.getChannel();
            FileOutputStream fileOutputStream = new FileOutputStream("pom_bak.xml");
            FileChannel outChannel = fileOutputStream.getChannel();

            try {
                while ((inChannel.read(buffer)) != -1) {
                    buffer.flip();
                    outChannel.write(buffer);
                    buffer.clear();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
